package com.agileboot.admin.controller.common;

import com.agileboot.domain.minio.UploadFileParamsDto;
import com.agileboot.domain.minio.UploadFileResultDto;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/minio")
public class MinIOController {
    @Autowired
    private MinioClient minioClient;
    //用于存储普通文件
    @Value("${minio.bucket.files}")
    private String bucket_mediafiles;
    //用于存储视频
    @Value("${minio.bucket.videofiles}")
    private String bucket_videofiles;

    @ApiOperation("上传图片")
    @PostMapping(value = "/upload")
    //,consumes = MediaType.MULTIPART_FORM_DATA_VALUE
    public UploadFileResultDto upload(@RequestPart("file") MultipartFile file) throws Exception {
        //准备数据
        UploadFileParamsDto uploadFileParamsDto = new UploadFileParamsDto();
        uploadFileParamsDto.setFilename(file.getOriginalFilename());
        uploadFileParamsDto.setFileSize(file.getSize());
        uploadFileParamsDto.setFileType("001001");
        //创建一个临时文件
        File tempFile = File.createTempFile("minio", ".temp");
        file.transferTo(tempFile);
        //文件路径
        String localFilePath = tempFile.getAbsolutePath();
//        Long companyId=1232141425L;
        //Long companyId, UploadFileParamsDto uploadFileParamsDto, String load FilePath
        UploadFileResultDto uploadFileResultDto = uploadFile(uploadFileParamsDto, localFilePath);
        return uploadFileResultDto;
    }

    public UploadFileResultDto uploadFile(UploadFileParamsDto uploadFileParamsDto, String loadFilePath) throws IOException {
        //先通过文件信息，拿到文件名
        String filename = uploadFileParamsDto.getFilename();
        //扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        //通过扩展名得到媒体资源类型 mimeType
        String mimeType = getMimeType(extension);
        //文件路径
        String defaultFolderPath = getDefaultFolderPath();

        String fileMd5 = getFileMd5(new File(loadFilePath));
        String objectName = defaultFolderPath + fileMd5 + extension;
        //调用上传文件的方法String localFilePath,String bucket,String objectName,String mimeType
        boolean result = getUploadObjectArgs(loadFilePath, mimeType, bucket_mediafiles, objectName);
        if (!result) {
            throw new RuntimeException("文件上传失败");
        }
        //入库文件信息

        //准备返回的对象
        String url =  "/" + bucket_mediafiles + "/" + objectName;
        UploadFileResultDto uploadFileResultDto = new UploadFileResultDto();
        uploadFileResultDto.setUrl(url);
        return uploadFileResultDto;
    }

    /**
     * 根据扩展名取出mimeType
     *
     * @param extension
     * @return
     */
    public String getMimeType(String extension) {
        if (extension == null) {
            extension = "";
        }
        //根据扩展名取出mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;//通用mimeType，字节流
        if (extensionMatch != null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }

    //获取文件默认存储目录路径 年/月/日
    private String getDefaultFolderPath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String folder = sdf.format(new Date()).replace("-", "/") + "/";
        return folder;
    }


    //得到分块文件的目录
    private String getChunkFileFolderPath(String fileMd5) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + "chunk" + "/";
    }

    //得到文件的MD5值
    private String getFileMd5(File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String fileMd5 = DigestUtils.md5Hex(fileInputStream);
            return fileMd5;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 上传文件到minio
     *
     * @param localFilePath 本地文件路径
     * @param bucket        桶名
     * @param objectName    对象名
     * @param mimeType      上传类型
     * @return
     */
    public boolean getUploadObjectArgs(String localFilePath, String mimeType, String bucket, String objectName) {
        //上传文件的参数信息
        try {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucket) //桶名
                    .filename(localFilePath) //指定本地路径
                    .object(objectName)  //对象名 放到子目录下
                    .contentType(mimeType)  //指定上传类型
                    .build();
            //上传文件
            minioClient.uploadObject(uploadObjectArgs);
            log.debug("上传文件到minio成功,上传文件成功，bucket:{},ObjectName:{}", bucket, objectName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件出错，bucket:{},ObjectName:{},错误信息:{}", bucket, objectName, e.getMessage());
        }
        return false;
    }
}
